<?php

// Ajax request legality check
require_once('config.php');
require_once('functions.php');

if( !check_ajax_referer() ) {
    header( 'Location: index.php' );
    exit(0);
}

session_start();

if( !isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0 ) {
    echo_json_answer( 999, ansi2utf($mxl_error_description[MXL_TIMEOUT_ERROR]) );   
    exit(0);
}

$user_id = $_SESSION['user_id'];

// ???????? ???????????? ?????????

	if( !isset($_REQUEST['oper']) || ( $oper = strip_tags(trim($_REQUEST['oper'])) ) != 'getenv' ||
        !isset($_REQUEST['items']) || ( $items = strip_tags(trim($_REQUEST['items'])) ) == '' )
        echo_json_and_die( $mxl_error_description[MXL_PROTOCOL_ERROR]);

    $itm = explode(',', $items, 64 );
    
// ??????????? ? ????? ??
    // ????????? ?????????? ???? ??????
    function db_exception_handler($exception) {
        echo_json_answer( 1, ansi2utf($mxl_error_description[MXL_DATABASE_ERROR]) );
        exit(1);
    }
    set_exception_handler('db_exception_handler');

    $db = new PDO("mysql:host=$host_name;dbname=$db_name", $db_user_name, $db_user_pass);

// ????????? ??????
    $items = $db->quote($itm[0]);
    for( $i=1; $i<count($itm); $i++ ) $items = $items.','.$db->quote($itm[$i]);
    
    $sqlstr = "SELECT entities_description.name as e_name, entities_description.entity_id as e_id, ".
              "entities_templates.locked as e_locked FROM entities_description LEFT JOIN entities_templates ON ".
              "entities_templates.entity_id=entities_description.entity_id AND ".
              "entities_templates.cat_id=".$_SESSION['cat_id']." ".
              "WHERE entities_description.name IN (".$items.")";

    if( ( $recset = $db->query( $sqlstr ) ) === false )
        echo_json_and_die( $mxl_error_description[MXL_DATABASE_ERROR]);

    $dataset = array('domain'=>$_SESSION['domain'], 'cat_id'=>$_SESSION['cat_id'], 'items'=>array() );
    
    while( $row = $recset->fetch(PDO::FETCH_OBJ) ) {
        for( $i=0; $i<count($itm); $i++) {
            if( $row->e_name == $itm[$i] ) {
                $dataset['items'][$i] = (bool)$row->e_locked;
                break;
            }
        }
    }
    
    $recset->closeCursor();
    echo json_encode( array( 'errcode'=>0, 'errmess'=>"Ok", 'data'=>$dataset ) );
    
exit(0);
?>
